<template>
  <div class='app-container'>
    <editor
      v-model="myValue"
      :init="init"
      :api-key="apiKey"
      :disabled="disabled"
      :style="styles"
    />
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'

// import 'tinymce/themes/modern/theme'
// import 'tinymce/skins/content/default/content.css'
import 'tinymce/themes/silver/theme.min.js'
import 'tinymce/icons/default/icons'

import "tinymce/themes/silver/theme";
import "tinymce/plugins/advlist"; //高级列表
import "tinymce/plugins/anchor"; //锚点
import "tinymce/plugins/autolink"; //自动链接
import "tinymce/plugins/autoresize"; //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import "tinymce/plugins/autosave"; //自动存稿
import "tinymce/plugins/charmap"; //特殊字符
import "tinymce/plugins/code"; //编辑源码
import "tinymce/plugins/codesample"; //代码示例
import "tinymce/plugins/directionality"; //文字方向
// import "tinymce/plugins/emoticons"; //表情
import "tinymce/plugins/fullpage"; //文档属性
// import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/help"; //帮助
import "tinymce/plugins/hr"; //水平分割线
import "tinymce/plugins/importcss"; //引入css
import "tinymce/plugins/insertdatetime"; //插入日期时间
import "tinymce/plugins/link"; //超链接
import "tinymce/plugins/lists"; //列表插件
import "tinymce/plugins/media"; //插入编辑媒体
import 'tinymce/plugins/image'; // 插入图片
import "tinymce/plugins/nonbreaking"; //插入不间断空格
import "tinymce/plugins/pagebreak"; //插入分页符
import "tinymce/plugins/paste"; //粘贴插件
import "tinymce/plugins/preview"; //预览
import "tinymce/plugins/print"; //打印
import "tinymce/plugins/quickbars"; //快速工具栏
import "tinymce/plugins/save"; //保存
import "tinymce/plugins/searchreplace"; //查找替换
// import 'tinymce/plugins/spellchecker'  //拼写检查，未加入汉化，不建议使用
import "tinymce/plugins/tabfocus"; //切入切出，按tab键切出编辑器，切入页面其他输入框中
import "tinymce/plugins/table"; //表格
import "tinymce/plugins/template"; //内容模板
import "tinymce/plugins/textcolor"; //文字颜色
import "tinymce/plugins/textpattern"; //快速排版
import "tinymce/plugins/toc"; //目录生成器
import "tinymce/plugins/visualblocks"; //显示元素范围
import "tinymce/plugins/visualchars"; //显示不可见字符
import "tinymce/plugins/wordcount"; //字数统计
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/imagetools"
import "tinymce/plugins/noneditable"
import {upload} from "@/api/common";


export default {
  name: "TinymceEditor",
  components: {
    Editor,
  },
  props: {
    // 传入一个value，使组件支持v-model绑定
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    /* 高度 */
    height: {
      type: Number,
      default: 600,
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null,
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false,
    },
    // 图片上传文件大小限制(MB)
    fileImageSize: {
      type: Number,
      default: 1,
    },
    fileImageType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg", "gif"],
    },
    // 图片上传文件大小限制(MB)
    fileFileSize: {
      type: Number,
      default: 5,
    },
    fileFileType: {
      type: Array,
      default: () => ["pdf", "zip", "rar", "7z", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "mp4"],
    },
    plugins: {
      type: [String, Array],
      default:
        "advlist anchor autolink autosave code codesample contextmenu directionality charmap anchor fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace tabfocus table template textcolor textpattern visualblocks visualchars wordcount ",
    },
    toolbar: {
      type: [String, Array],
      default: () => {
        return [
          "undo redo removeformat | searchreplace bold italic underline strikethrough | colorpicker fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent | ltr rtl | bullist numlist | forecolor backcolor blockquote | pagebreak | ",
          "insertfile link image media subscript superscript codesample | hr charmap anchor insertdatetime table | fullscreen preview print",
        ]
      },
    },
    fontsizeFormats: {
      type: String,
      default: "12px 14px 16px 18px 24px 36px 48px 56px 72px"
    },
    fontFormats: {
      type: String,
      default: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings"
    }
  },
  data() {
    return {
      apiKey: "jzlds2e6urz6akm9wxp4f70mnwg83d8fovsialqazxowyity",
      // 配置文件服务器的静态访问路径前缀
      // static_web_preurl: 'http://localhost/files/hxzy_img/',
      // 初始化配置
      init: {
        placeholder: "在这里输入文字",
        language_url: "/static/tinymce/langs/zh_CN.js",// 这个文件会放在下面
        language: "zh_CN",
        // 必须添加 '/tinymce/skins/content/default/content.min.css'。否则 fontselect 默认不显示“系统字体”。
        content_css: [`/static/tinymce/skins/ui/oxide/content.min.css`, `/static/tinymce/skins/content/default/content.min.css`],
        skin_url: "/static/tinymce/skins/ui/oxide",
        height: this.height,
        // images_file_types: this.fileImageType.join(","),
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        // imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        media_live_embeds: true,
        content_style: "img {max-width:100%;}", // 直接自定义可编辑区域的css样式
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        // @ts-nocheckplugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
        plugins: this.plugins,
        // toolbar:'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat | table',
        toolbar: this.toolbar,
        fontsize_formats: this.fontsizeFormats,//"8pt 10pt 12pt 14pt 18pt 24pt 36pt", // 第二步
        font_formats: this.fontFormats,
        branding: false,
        menubar: false,
        file_picker_types: "file media",// 三个参数分别对应三个插件【link，image，media】，如果要屏蔽某个插件的上传，就去掉对应参数
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: async (blobInfo, success, failure) => {
          //  let formdata = new FormData()
          // formdata.set('file', blobInfo.blob())
          if (await !this.validateImage(blobInfo.blob())) {
            failure("检查图片失败!")
            return
          }
          const {url, name} = await this.uploadFile(blobInfo.blob(), 'image')
          success(url, {alt: name, title: name})
          // this.handleImgUpload(blobInfo, success, failure)
        },
        file_picker_callback: (callback, value, meta) => {
          // 创建一个隐藏的type=file的文件选择input
          const input = document.createElement('input')
          input.setAttribute('type', 'file')
          input.setAttribute('accept', this.fileFileType.map((item) => {
            return '.' + item
          }).join(','))
          // 触发点击
          input.click()
          input.onchange = async (e) => {
            const file = e.originalTarget.files[0]// 只选取第一个文件。如果要选取全部，后面注意做修改
            if (await this.validateFile(file)) {
              const {url, name} = await this.uploadFile(file, meta.filetype)
              // Provide alternative source and posted for the media dialog
              if (meta.filetype == 'media') {
                // callback('movie.mp4', {source2: 'alt.ogg', poster: 'image.jpg'});
                callback(url, {title: name})
              }
              // 当点击meidia图标上传时,判断meta.filetype == 'media'有必要，因为file_picker_callback是media(媒体)、image(图片)、file(文件)的共同入口
              if (meta.filetype == 'file') {
                // callback('mypage.html', {text: 'My text'});
                callback(url, {text: name});
              }
              // Provide image and alt text for the image dialog
              if (meta.filetype == 'image') {
                // callback('myimage.jpg', {alt: 'My alt text'});
                callback(url, {alt: name});
              }
            }
          }
        }
      },
      myValue: this.value,
    }
  },
  computed: {
    styles() {
      let style = {};
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`;
      }
      if (this.height) {
        style.height = `${this.height}px`;
      }
      return style;
    },
  },
  watch: {
    value(newValue) {
      this.myValue = newValue
    },
    myValue(newValue) {
      this.$emit("input", newValue);
    },
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    // 图片校验
    async validateImage(file) {
      let isImg = false;
      if (this.fileImageType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileImageType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileImageType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileImageSize) {
        const isLt = file.size / 1024 / 1024 < this.fileImageSize;
        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileImageSize} MB!`);
          return false;
        }
      }
      return true
    },
    // 校验视频
    async validateFile(file) {
      let isFile = false;
      if (this.fileFileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isFile = this.fileFileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isFile = file.type.indexOf("image") > -1;
      }

      if (!isFile) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileFileType.join("/")}格式文件!`);
        return false;
      }

      if (this.fileFileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileFileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileFileSize} MB!`);
          return false;
        }
      }
      // const duration = await this.getVideoDuration(file)
      // if (duration > 60) {
      //   this.$message.error('上传视频时长不能超过 60 秒！')

      //   return false
      // }

      return true
    },
    /**
     * @description 获取视频时长
     * @param {File} file - 要上传的文件
     * @returns {Promise<number>}
     */
    getVideoDuration(file) {
      return new Promise(resolve => {
        const videoElement = document.createElement('video')
        videoElement.src = URL.createObjectURL(file)

        videoElement.addEventListener('loadedmetadata', () => {
          resolve(videoElement.duration)
        })
      })
    },
    /**
     * @description 上传文件
     * @param {File} file - 要上传的文件
     * @param {string} type - 文件类型
     * @returns {Object}
     */
    async uploadFile(file, type = 'images') {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let formData = new FormData();
      formData.append("uploadFile", file);
      const res = await upload(formData);
      loading.close()
      if (res.code == 200) {
        return {url: res.data.url, name: file.name}
      } else {
        return this.$message.error(res.msg)
      }

      // // 注：此为调用后端上传接口，需根据实际情况进行调整
      // const res = await fileUpload(formData)
      // loading.close()
      // if (res.code !== 1) return this.$message.error(res.$message)
      // return {
      //   url: `${ROOT}/${res.data}`,
      //   name: file.name
      // }
    },
    // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    // 需要什么事件可以自己增加
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.myValue = "";
    },
  },
}
</script>

<style scoped>

</style>
